package cn.wolfcode.crm.web.interceptor;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.util.RequiredPermission;
import cn.wolfcode.crm.util.StringUtils;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

public class PermissionInterception implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee employee = UserContext.getEmployee();
        if(employee.isAdmin()){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if(!method.isAnnotationPresent(RequiredPermission.class)){
            return true;
        }
        List<String> expressions = UserContext.getExpressions();
        String expression = StringUtils.getExpression(method);
        if(expressions.contains(expression)){
            return true;
        }
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").
                forward(request,response);
        return false;
    }
}
